﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Tool.Forms;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;

namespace ERP_RORZE_TOOL.Tool.UserControls
{
	public partial class ucReturn : DevExpress.XtraEditors.XtraUserControl
	{
		private int index = 0;
		public int _action = 1;
        ReturnHelper helper=new ReturnHelper(new Return());
        public GridView GridView;
        DXPopupMenu menu;

		#region Handle Methods

		public ucReturn()
		{
            InitializeComponent();
            InitDateRangeMenu();
            BindDatatoGrid();
            gridView1.BestFitColumns();
            this.dropbtDateRange.DropDownControl = menu;
            this.dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.SixMonths;
		}

		private void btAddNew_Click_1(object sender, EventArgs e)
		{
			AddNew();
		}

		private void btEdit_Click_1(object sender, EventArgs e)
		{
			EditRow();
		}

		private void btDelete_Click_1(object sender, EventArgs e)
		{
			DeleteRows();
		}


		private void gridView1_CustomDrawEmptyForeground_1(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
		{
			if(gridView1.RowCount != 0)
				return;

			StringFormat drawFormat = new StringFormat();

			drawFormat.Alignment = drawFormat.LineAlignment = StringAlignment.Center;

			e.Graphics.DrawString("No items exist in this view", e.Appearance.Font, SystemBrushes.ControlDark, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), drawFormat);

		}

		private void gridView1_DoubleClick_1(object sender, EventArgs e)
		{
			var gridView = (GridView)sender;
			var point = gridView.GridControl.PointToClient(Control.MousePosition);

			DoDoubleClick(gridView, point);
		}


		private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddNew();
		}

		private void editToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditRow();
		}

		private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
		{
			DeleteRows();
		}
		#endregion

        public void BindDatatoGrid(int range = 1)
		{
			ReturnHelper helper = new ReturnHelper(new Return());
			DataTable dt = helper.GetAll(range);

			gridControl1.DataSource = dt;
            gridView1.BestFitColumns();
            this.GridView = gridView1;
			Utilities.GridUtil.SelectRow(gridView1, index, _action);
		}

		private void DoDoubleClick(GridView v, Point p)
		{
			Cursor.Current = Cursors.WaitCursor;
			_action = 1;
			index = gridView1.FocusedRowHandle;
			var info = v.CalcHitInfo(p);
			if(info.InRow || info.InRowCell)
			{
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

				int iD = int.Parse(row[0][ToolConstants.Entities.Return.FieldName.ID].ToString());
			    helper.ValueObject.ID = iD;
                helper.LoadOne();

				frm_ReturnEdit fr = new frm_ReturnEdit(this);
				fr.Id = iD;
				fr.Date = helper.ValueObject.Date;
                fr.ToolId = helper.ValueObject.ToolID;
                fr.StatusName = helper.ValueObject.StatusName;
                fr.Staff = helper.ValueObject.StaffID;
                fr.Machine = helper.ValueObject.MachineID;
                fr.Quantity = helper.ValueObject.Quantity;
                fr.Note = helper.ValueObject.Note;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
			}
			Cursor.Current = Cursors.Default;
		}

		private void DeleteRows()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				Cursor.Current = Cursors.WaitCursor;
				var row = new DataRow[gridView1.SelectedRowsCount];
				var ReturnId = new int[gridView1.SelectedRowsCount];

				for(int i=0; i< gridView1.SelectedRowsCount; i++)
				{
					row[i]= gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
					ReturnId[i] = int.Parse(row[i][ToolConstants.Entities.Return.FieldName.ID].ToString());
				}


				if(MessageBox.Show(ToolConstants.Message.DeleteQuestion, ToolConstants.Form.MessageBox.Warning,
								MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
				{
					ReturnHelper helper = new ReturnHelper(new Return());
					for(int i = 0; i < ReturnId.Length; i++)
					{
						helper.ValueObject.ID = ReturnId[i];
						if(helper.Delete() >0)
						{
							_action = 2;
						}
						else
						{
							MessageBox.Show(ToolConstants.Message.DeleteFailed, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					}

                    BindDatatoGrid();

				}
				Cursor.Current = Cursors.Default;
			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void EditRow()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				Cursor.Current = Cursors.WaitCursor;
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

				index = gridView1.FocusedRowHandle;
				_action = 1;

				int iD = int.Parse(row[0][ToolConstants.Entities.Return.FieldName.ID].ToString());
                helper.ValueObject.ID = iD;
                helper.LoadOne();

                frm_ReturnEdit fr = new frm_ReturnEdit(this);
                fr.Id = iD;
                fr.Date = helper.ValueObject.Date;
                fr.ToolId = helper.ValueObject.ToolID;
                fr.StatusName = helper.ValueObject.StatusName;
                fr.Staff = helper.ValueObject.StaffID;
                fr.Machine = helper.ValueObject.MachineID;
                fr.Quantity = helper.ValueObject.Quantity;
                fr.Note = helper.ValueObject.Note;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
				Cursor.Current = Cursors.Default;

			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void AddNew()
		{
			Cursor.Current = Cursors.WaitCursor;
			Form fr = new frm_ReturnAdd(this);
            fr.StartPosition = FormStartPosition.CenterParent;
			fr.ShowDialog();
			Cursor.Current = Cursors.Default;
		}

        private void btRefresh_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            BindDatatoGrid();
            Cursor.Current = Cursors.Default;
        }

        private void gridControl1_ProcessGridKey(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteRows();
            }
        }

        private void btImport_Click(object sender, EventArgs e)
        {
            FileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;

            int rowCount = 0;

            INISettings iniSettings = new INISettings();
            string connectString = iniSettings.SQLConnectionString;
            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = null;

            // Create DbDataReader to Data Worksheet
            DbDataReader dr = null;

            // Bulk Copy to SQL Server 
            SqlBulkCopy bulkInsert = new SqlBulkCopy(connectString);

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    string path = fileDialog.FileName;

                    // Connection String to Excel Workbook
                    string excelConnectionString =
                        string.Format(
                            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False",
                            path);

                    connection.ConnectionString = excelConnectionString;
                    connection.Open();

                    command = new OleDbCommand("select  COUNT(*) from [Sheet1$]", connection);
                    rowCount = (int)command.ExecuteScalar();

                    command = new OleDbCommand("select * from [Sheet1$]", connection);
                    dr = command.ExecuteReader();

                    bulkInsert.DestinationTableName = ToolConstants.DatabaseName + ".[dbo].[" + ToolConstants.Entities.Return.Name + "]";

                    SqlBulkCopyColumnMapping date = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.Date, ToolConstants.Entities.Return.FieldName.Date);
                    bulkInsert.ColumnMappings.Add(date);

                    SqlBulkCopyColumnMapping staffID = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.StaffID, ToolConstants.Entities.Return.FieldName.StaffID);
                    bulkInsert.ColumnMappings.Add(staffID);

                    SqlBulkCopyColumnMapping machineId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.MachineID, ToolConstants.Entities.Return.FieldName.MachineID);
                    bulkInsert.ColumnMappings.Add(machineId);

                    SqlBulkCopyColumnMapping toolId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.ToolID, ToolConstants.Entities.Return.FieldName.ToolID);
                    bulkInsert.ColumnMappings.Add(toolId);

                    SqlBulkCopyColumnMapping statusId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.StatusName, ToolConstants.Entities.Return.FieldName.StatusName);
                    bulkInsert.ColumnMappings.Add(statusId);

                    SqlBulkCopyColumnMapping quantity = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.Quantity, ToolConstants.Entities.Return.FieldName.Quantity);
                    bulkInsert.ColumnMappings.Add(quantity);

                    SqlBulkCopyColumnMapping note = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Return.FieldName.Note, ToolConstants.Entities.Return.FieldName.Note);
                    bulkInsert.ColumnMappings.Add(note);

                    Cursor.Current = Cursors.WaitCursor;
                    bulkInsert.WriteToServer(dr);
                    Cursor.Current = Cursors.Default;

                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.Return, string.Format(ToolConstants.Message.ImportSuccessfullyLog, rowCount.ToString()));
                    DialogResult message = MessageBox.Show(string.Format(ToolConstants.Message.ImportSuccessfully, rowCount.ToString()),
                                                           ToolConstants.Form.MessageBox.Message,
                                                           MessageBoxButtons.OKCancel);
                    if (message == DialogResult.OK)
                    {
                        BindDatatoGrid();
                    }

                }
                catch (Exception exception)
                {
                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.Return, string.Format(ToolConstants.Message.ImportFailedLog, exception.Message));
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    if (connection != null && connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }


        protected virtual void InitDateRangeMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.SixMonths, new EventHandler(OnItemClick6Months), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.OneYear, new EventHandler(OnItemClick1Year), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.TwoYears, new EventHandler(OnItemClick2Years), null, null, null, null));
            menu.Items.Add(new DXMenuItem(ToolConstants.Configuration.DateRangeTitle.AllTime, new EventHandler(OnItemClickAllTime), null, null, null, null));

        }

        void OnItemClick6Months(object sender, EventArgs e)
        {
            BindDatatoGrid(1);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.SixMonths;
        }

        void OnItemClick1Year(object sender, EventArgs e)
        {
            BindDatatoGrid(2);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.OneYear;
        }

        void OnItemClick2Years(object sender, EventArgs e)
        {
            BindDatatoGrid(3);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.TwoYears;
        }

        void OnItemClickAllTime(object sender, EventArgs e)
        {
            BindDatatoGrid(0);
            dropbtDateRange.Text = ToolConstants.Configuration.DateRangeTitle.AllTime;
        }

        private void checkboxShowFooter_CheckedChanged(object sender, EventArgs e)
        {
            if (gridView1.OptionsView.ShowFooter == true)
            {
                gridView1.OptionsView.ShowFooter = false;
            }
            else
            {
                gridView1.OptionsView.ShowFooter = true;
            }
        }
	}
}
